<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">

      <sticky :z-index="10" :class-name="'sub-navbar '+postForm.status">
        <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm">
          保存
        </el-button>
        <el-button v-loading="loading" type="warning" @click="cancle">
          取消
        </el-button>
      </sticky>

      <div class="createPost-main-container">
        <el-row>
          <el-col :span="24">

            <div class="postInfo-container">
              <el-row>
                <el-form-item style="margin-bottom: 30px;" prop="title">
                  标题  <el-input v-model="postForm.title" style="width: 350px" />
                </el-form-item>

                <el-form-item style="margin-bottom: 30px;" prop="template">
                  模板
                  <el-select v-model="postForm.template" placeholder="请选择模板" clearable style="width: 350px">
                    <el-option key="1" label="模板1" value="1" />
                    <el-option key="2" label="模板2" value="2" />
                  </el-select>
                </el-form-item>

                <el-form-item style="margin-bottom: 30px;" prop="description">
                  简述  <el-input
                  type="textarea"
                  :rows="2"
                  style="width: 350px"
                  placeholder="请输入专题简单叙述"
                  v-model="postForm.description">
                </el-input>
                </el-form-item>

                <el-form-item style="margin-bottom: 30px;" prop="picUrl">
                  图片  <el-upload
                  class="avatar-uploader"
                  action="http://localhost:8280/file"
                  :show-file-list="false"
                  :on-success="handleUploadImgSuccess">
                  <img v-if="postForm.picUrl" :src="postForm.picUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
                </el-form-item>

              </el-row>
            </div>
          </el-col>
        </el-row>

      </div>
    </el-form>
  </div>
</template>

<script>
  import Tinymce from '@/components/Tinymce'
  import MDinput from '@/components/MDinput'
  import Sticky from '@/components/Sticky' // 粘性header组件
  import { validURL } from '@/utils/validate'
  import { saveTheme } from '@/api/theme'

  const defaultForm = {
    title: '', // 专题标题
    template: '',//模板编号
    picUrl: '', // 专题图片
    description: '',//专题描述
  }

  export default {
    name: 'ThemeDetail',
    components: { Tinymce, MDinput, Sticky },
    props: {
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {
      const validateRequire = (rule, value, callback) => {
        if (value === '') {
          this.$message({
            message: rule.field + '为必传项',
            type: 'error'
          })
          callback(new Error(rule.field + '为必传项'))
        } else {
          callback()
        }
      }
      const validateSourceUri = (rule, value, callback) => {
        if (value) {
          if (validURL(value)) {
            callback()
          } else {
            this.$message({
              message: '外链url填写不正确',
              type: 'error'
            })
            callback(new Error('外链url填写不正确'))
          }
        } else {
          callback()
        }
      }
      return {
        statusMap: { 1: '上线中', 2: '已下线' },
        postForm: Object.assign({}, defaultForm),
        loading: false,
        userListOptions: [],
        rules: {
          image_uri: [{ validator: validateRequire }],
          title: [{ validator: validateRequire }],
          content: [{ validator: validateRequire }],
          source_uri: [{ validator: validateSourceUri, trigger: 'blur' }]
        },
        tempRoute: {}
      }
    },
    computed: {
    },
    created() {
      if (this.isEdit) {
        const id = this.$route.params && this.$route.params.id
        this.fetchData(id)
      } else {
        this.postForm = Object.assign({}, defaultForm)
      }

      // Why need to make a copy of this.$route here?
      // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
      // https://github.com/PanJiaChen/vue-element-admin/issues/1221
      this.tempRoute = Object.assign({}, this.$route)
    },
    methods: {
      fetchData(id) {
        fetchNews(id).then(response => {
          this.postForm = response.data

          this.setTagsViewTitle()

          // set page title
          this.setPageTitle()
        }).catch(err => {
          console.log(err)
        })
      },
      setTagsViewTitle() {
        const title = '编辑专题'
        const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.postForm.id}` })
        this.$store.dispatch('tagsView/updateVisitedView', route)
      },
      setPageTitle() {
        const title = '编辑专题'
        document.title = `${title} - ${this.postForm.id}`
      },
      submitForm() {
        console.log(this.postForm)
        this.$refs.postForm.validate(valid => {
          if (valid) {
            saveTheme(this.postForm).then(r1 => {
              this.loading = false
              this.$notify({
                title: '成功',
                message: '发布成功',
                type: 'success',
                duration: 2000
              })
              //返回列表页面
              this.goBack();
            })

            //
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      cancle() {
        this.goBack()
      },
      handleUploadImgSuccess(e) {
        this.postForm.picUrl = e.data.url
      },
      //关闭标签并返回列表页
      goBack(){
        this.$store.dispatch('tagsView/delView', this.$route).then(() => {
          this.$nextTick(() => {
            this.$router.replace({
              path: '/theme/list'
            })
          })
        })
      }
    },

  }
</script>

<style lang="scss" scoped>
  @import "~@/styles/mixin.scss";

  .createPost-container {
    position: relative;

    .createPost-main-container {
      padding: 40px 45px 20px 50px;

      .postInfo-container {
        position: relative;
        @include clearfix;
        margin-bottom: 10px;

        .postInfo-container-item {
          float: left;
        }
      }
    }

  }
  /*图片*/
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    border: 1px solid #d9d9d9;
    font-size: 28px;
    color: #8c939d;
    width: 450px;
    height: 180px;
    line-height: 180px;
    text-align: center;
  }
  .avatar {
    border: 1px solid #d9d9d9;
    width: 450px;
    height: 180px;
    display: block;
  }
</style>
